<template>
	<view class="Global">
		<!-- 背景图片铺满 -->
		<!-- <image class="imagepage" src="/static/background@2x.png" mode=""></image> -->
		<bgImage></bgImage>
		<MyNav :title="title" bgColor="" :backIcon="isback"></MyNav>


		<button class='button' hover-class="hover" @click="startSearch()" > 搜索蓝牙设备 </button>
<!--		<text class="td">（Android8.0+系统需开启定位）</text>-->
		<scroll-view class="device_list" >
			<view v-for="(item,index) in list" @click="bindViewTap(item)" class="item" hover-class="item_hover">

				<view >{{item.name}}</view>
				<view >{{item.deviceId}}</view>
				<view >信号强度: {{item.RSSI}}dBm</view>
			</view>
		</scroll-view>

	</view>
</template>

<script>
	import MyNav from '@/components/customnavbar.vue'
	import bgImage from '@/components/backgroundImage.vue'
	var app = getApp()
	export default {
		components: {
			MyNav,
			bgImage


		},

		data() {
			return {
				title: '蓝牙搜索',
				isback: true,

				list: [],
				services: [],
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false,
				isScanning: false,


				BLEInformation: {
					platform: "",
					deviceId: "",
					writeCharaterId: "",
					writeServiceId: "",
					notifyCharaterId: "",
					notifyServiceId: "",
					readCharaterId: "",
					readServiceId: "",
				}

			}
		},
		methods: {


			//搜索设备
			startSearch() {
				this.list=[]
				var that = this
				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success:(res) =>{
								console.log('openBluetoothAdapter success', res)
								uni.showToast({
									title: '刷新'
								});
								if (res.available) {
									if (res.discovering) {
										uni.stopBluetoothDevicesDiscovery({
											success(res) {
												console.log(res)
											}
										})
									} else {
										// that.startBluetoothDevicesDiscovery()
										that.getBluetoothDevices()
									}
									// that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
										showCancel: false
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: '调用失败'
								});
							}
						})
					},
					fail() {

						// if (res.errCode === 10001) {
						//   uni.onBluetoothAdapterStateChange(function (res) {
						//     console.log('onBluetoothAdapterStateChange', res)
						//     if (res.available) {
						//       this.startBluetoothDevicesDiscovery()
						//     }
						//   })
						// }

						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败，请到设置打开蓝牙',
							showCancel: false
						})
					}
				})
			},

			getBluetoothDevices() { //获取蓝牙设备信息
				var that = this
				console.log("start search")
				uni.showLoading({
					title: '正在加载中',
					icon: 'loading',
				})
				that.isScanning=true
				uni.startBluetoothDevicesDiscovery({
					success:(res)=> {
						// console.log(res)

						setTimeout(function() {
							that.getBluetoothDevicesData()
						}, 5000)
					},
					fail: () => {
						uni.showToast({
							title: '调用失败11'
						});
					}
				})
			},

			getBluetoothDevicesData(){
				var that = this
				uni.getBluetoothDevices({
					success:(res)=>  {
						/* var devices = []
						var num = 0
						for (var i = 0; i < blueRes.devices.length; ++i) {
							if (blueRes.devices[i].name != "未知设备") {
								devices[num] = blueRes.devices[i]
								num++
							}
						} */
						/* that.setData({
							list: devices,
							isScanning: false
						}) */


						/* uni.showModal({
							title: '',
							content: JSON.stringify(res.devices),
							showCancel: true,
							cancelText: '取消',
							confirmText: '确认',
							success: res => {},
							fail: () => {},
							complete: () => {}
						}); */
            console.log('getBluetoothDevices',res)
						  that.list=[...that.list,...res.devices]
            // 使用filter和findIndex进行去重
            let uniqueDataList = that.list.filter((item, index, self) => {
              // 返回第一个匹配项的索引，用于判断当前项是否为第一个匹配项
              const firstIndex = self.findIndex((obj) => obj.deviceId === item.deviceId);

              // 如果当前项是第一个匹配项，则保留，否则过滤掉
              return index === firstIndex;
            });
            that.list = uniqueDataList;

						 /*  uni.showModal({
						   	title: '',
						   	content: JSON.stringify(that.list),
						   	showCancel: false,
						   	cancelText: '',
						   	confirmText: '数据',
						   	success: res => {},
						   	fail: () => {},
						   	complete: () => {}
						   }); */

						  uni.hideLoading()
						  uni.stopPullDownRefresh()
						  uni.stopBluetoothDevicesDiscovery({
						  	success(res) {
						  		console.log("停止搜索蓝牙")
						  	}
						  })
						/* that.list=[...that.list,...res.devices]
						that.isScanning=false
						uni.hideLoading()
						uni.stopPullDownRefresh()
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								console.log("停止搜索蓝牙")
							}
						}) */
					},
					fail: (res) => {
						uni.showToast({
							title: '调用失败'
						});
					},
					complete: () => {
						/* uni.showToast({
							title:'完成调用'
						}) */
					}
				})
			},
			bindViewTap(e) {
				var that = this
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
					},
				})
				/* that.setData({
					serviceId: 0,
					writeCharacter: false,
					readCharacter: false,
					notifyCharacter: false
				}) */
				that.serviceId=0
				that.writeCharacter=false
				that.readCharacter=false
				that.notifyCharacter=false

				// console.log(e.currentTarget.dataset.title)
				uni.showLoading({
					title: '正在连接',

				})
				uni.createBLEConnection({
					deviceId: e.deviceId,
					success(res) {
						console.log(res)


					/* 	uni.showModal({
							title: '',
							content: JSON.stringify(res)+"\t"+e.deviceId,
							showCancel: false,
							cancelText: '',
							confirmText: 'BLE',
							success: res => {},
							fail: () => {},
							complete: () => {}
						}); */
						// app.BLEInformation.deviceId = e.deviceId
					that.BLEInformation.deviceId=e.deviceId
						that.getSeviceId(e.deviceId)

					},
					fail(e) {
						uni.showModal({
							title: '提示',
							content: '连接失败',
							showCancel: false
						})
						console.log(e)
						uni.hideLoading()
					},
					complete(e) {
						console.log(e)
					}
				})
			},
			getSeviceId(e) {
				var that = this
				/* var platform = app.BLEInformation.platform
				console.log(app.BLEInformation.deviceId) */
				uni.getBLEDeviceServices({
					deviceId: e,
					success(res) {
						console.log(res)
						// var realId = ''
						// if (platform == 'android') {
						//   // for(var i=0;i<res.services.length;++i){
						//   // var item = res.services[i].uuid
						//   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
						//   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
						//   //       break;
						//   //     }
						//   // }
						// } else if (platform == 'ios') {
						//   // for(var i=0;i<res.services.length;++i){
						//   // var item = res.services[i].uuid
						//   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
						//   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
						//   // break
						//   // }
						//   // }
						// }
						// app.BLEInformation.serviceId = realId

						/* uni.showModal({
							title: '',
							content: JSON.stringify(res),
							showCancel: false,
							cancelText: '',
							confirmText: 'UUID',
							success: res => {},
							fail: () => {},
							complete: () => {}
						}); */

						// that.services=res.services
						that.getCharacteristics(res.services)
					},
					fail(e) {
						console.log(e)
						uni.showModal({
							title: '调用失败1',
							content: JSON.stringify(e),
							showCancel: false,
							cancelText: '',
							confirmText: '确认',
							success: res => {},
							fail: () => {},
							complete: () => {}
						});
					},
					complete(e) {
						console.log(e)
					}
				})
			},
			getCharacteristics(e) {



				var that = this
				var list = e
				var num = that.serviceId
				var write = that.writeCharacter
				var read = that.readCharacter
				var notify = that.notifyCharacter


				uni.getBLEDeviceCharacteristics({
					deviceId: that.BLEInformation.deviceId,
					serviceId: list[num].uuid,
					success(res) {
						console.log(res)
						/* uni.showModal({
							title: '',
							content: JSON.stringify(res),
							showCancel: false,
							cancelText: '',
							confirmText: 'chara',
							success: res => {},
							fail: () => {},
							complete: () => {}
						}); */

						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									that.BLEInformation.notifyCharaterId = item
									that.BLEInformation.notifyServiceId = list[num].uuid
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									that.BLEInformation.writeCharaterId = item
									that.BLEInformation.writeServiceId = list[num].uuid
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									that.BLEInformation.readCharaterId = item
									that.BLEInformation.readServiceId = list[num].uuid
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.setData({
								writeCharacter: write,
								readCharacter: read,
								notifyCharacter: notify,
								serviceId: num
							})
							if (num == list.length) {
								uni.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
									showCancel: false
								})
							} else {
								that.getCharacteristics(e)
							}
						} else {
							uni.showToast({
								title: '连接成功',
							})
							that.openControl()
						}
					},
					fail(e) {
						console.log(e)
						uni.showModal({
							title: '连接失败',
							content: JSON.stringify(e),
							showCancel: false,
							cancelText: '',
							confirmText: '确认',
							success: res => {},
							fail: () => {},
							complete: () => {}
						});
					},
					complete(e) {
						console.log("write:" + that.BLEInformation.writeCharaterId)
						console.log("read:" + that.BLEInformation.readCharaterId)
						console.log("notify:" + that.BLEInformation.notifyCharaterId)
					}
				})
			},
			openControl() { //连接成功返回主页
				uni.navigateTo({
					url: '/subPack/bluetooth/printLabel/printLabel?item=' +
						encodeURIComponent(JSON.stringify(this.BLEInformation)),
				})

			},

		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad() {

		/* 	uni.getLocation({
				type: 'wgs84',
				success(res) {
					console.log('开启定位权限', res)
				},
				fail: (err) => {
					uni.showToast({
						title: '请先打开定位功能:' + err,
						duration: 1500
					});
				}
			});  */

			/* const app2 = getApp();
			uni.getSystemInfo({
				success: (res) => {

					console.log('获取平台', res.platform);
					app2.BLEInformation.platform = res.platform
				}
			}) */
		}
	}
</script>

<style>
	.button {
		margin-top: 20rpx;
		width: 90%;
		background-color: #54bec2;
		color: white;
		border-radius: 98rpx;
		background: bg_red;
	}

	/* 按下变颜色 */
	.hover {
		background: #DCDCDC;
	}

	.device_list {

		margin-left: 20rpx;
		margin-right: 20rpx;
		margin-top: 10rpx;
		margin-bottom: 20rpx;
		border: 1rpx solid #EEE;
		border-radius: 5rpx;

	}

	.td {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 10rpx;
	}

	/* .item {
    padding-top: 10px;
    padding-bottom: 10px;
     height: 130rpx;
     width: 100%;
} */
	.item {
		display: block;
		/* font-family:  Arial, Helvetica, sans-serif;
  font-size:14px;
  margin: 0 10px;
  margin-top:10px;
  margin-bottom: 10px;
  background-color:#FFA850;
  border-radius: 5px;
  border-bottom: 2px solid #68BAEA; */
		border-bottom: 1rpx solid #EEE;
		padding: 4rpx;
		color: #666;
	}

	.item_hover {
		background-color: rgba(0, 0, 0, .1);
	}

	.block {
		display: block;
		color: #ffffff;
		padding: 5rpx;
	}

	/* pages/bleConnect/bleConnect.wxss */
</style>
